package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.exception.LoginException;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.SellerService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {

    @DubboReference
    private SellerService sellerService;

    @RequestMapping("login")
    public String login(){
        return "shoplogin";
    }

    @RequestMapping("index")
    public String index(){
        return "admin/index";
    }

    @RequestMapping("home")
    public String home(){
        return "admin/home";
    }

    @RequestMapping("register")
    public String register(){
        return "register";
    }

    @RequestMapping("sampling")
    public String sampling(){
        return "sampling";
    }

    @RequestMapping("goods_edit")
    public String goods_edit(){
        return "admin/goods_edit";
    }

    @RequestMapping("getInfo")
    @ResponseBody
    public Result getInfo(TbSeller tbSeller){

//        request.getSession().setAttribute("SellerId",tbSeller.getSellerId());

        Map<String,Object> map = new HashMap<>();

        //1.创建subject对象
        Subject subject = SecurityUtils.getSubject();

        //2.封装用户的账号密码 —> token对象
        UsernamePasswordToken token = new UsernamePasswordToken(tbSeller.getSellerId(),tbSeller.getPassword());

        //3.执行登录功能,调用subject的login方法
        //shiro是通过抛异常的方式来提示账号不存在或者密码错误
        try {
            subject.login(token);
        }catch (UnknownAccountException u){
            return Result.response(ResultEnum.NOTID);
        }catch (IncorrectCredentialsException i){
            return Result.response(ResultEnum.PASSWORD_ERROR);
        }catch (LoginException l){
            return Result.response(ResultEnum.EXAMIN);
        }

        return Result.response(ResultEnum.SUCCESS);

    }
}
